using System.Net.Sockets;
using System.IO;

using GSN.Mail.Messages;

namespace GSN.Mail
{
    class IMAPClient
    {
        private TcpClient tcpClient = null;
        private int imapCommandCounter = 0;
        private StreamReader sr = null;
        private const string SERVER_OK_RESPONSE = "* OK";
        private const string COMMAND_OK_RESPONSE = "OK";
        private const string COMMAND_BAD_RESPONSE = "BAD";
        private const string COMMAND_NO_RESPONSE = "NO";

        public IMAPClient()
        {
            tcpClient = new TcpClient();
        }

        public bool connect(string server, int port)
        {
            tcpClient.Connect(server, port);
            sr = new StreamReader(tcpClient.GetStream());
            string response = sr.ReadLine();
            bool result = response.StartsWith(SERVER_OK_RESPONSE);
            if (result)
            {
                // connected ok, check capibilites
                sendCommand("CAPABILITY");
            }

            return result;
        }

        private void sendCommand(string cmd)
        {
            ++imapCommandCounter;
            string sCmd = string.Format("{0}{1}", getPrefix(), cmd);
            
        }

        private string getPrefix()
        {
            return string.Format("IMAP{0} ", imapCommandCounter.ToString("000"));
        }

        private bool readResponse()
        {
            bool doRead = true;
            bool result = false;
            string line = null;
            while (doRead)
            {
                line = sr.ReadLine();
                if (line.StartsWith(getPrefix() + COMMAND_OK_RESPONSE))
                {
                    result = true;
                    doRead = false;
                }
                else if (line.StartsWith(getPrefix() + COMMAND_NO_RESPONSE))
                {
                    result = false;
                    doRead = false;
                }
                else if (line.StartsWith(getPrefix() + COMMAND_BAD_RESPONSE))
                {
                    result = false;
                    doRead = false;
                }
            }

            return result;
        }

        public void disconnect()
        {
            tcpClient.Close();
        }

        public void login()
        {
        }

        public Message[] peek()
        {
            return null;
        }
    }
}
